// 引入接口文件
import {
    deleteFun,
    findProduct,
  } from './competingGoodsListServ'
  import { message } from 'antd'
  import {cloneDeep} from 'lodash'
  
  const defultState = {
      biz:{
        queryForm: {}
      },
      areaList: [],
      products: [],
      goods: []
  }
  
  const tmpModule = {
    state: cloneDeep(defultState),
    subscriptions: {
      setup ({dispatch, history}) {
        history.listen(({ pathname, query }) => {
          if('' + tmpModule.pathname === '' + pathname){
            dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
            dispatch({type: 'findProduct',payload: {}})
          }
        })
      },
    },
  
  
    effects: {
      *findProduct({payload},{put,select,call}){
        let {areaList} = yield select(state => state[tmpModule.namespace])
        let params = {
          userId: localStorage.username
        }
        const { success, msg, projectList } = yield call(findProduct, {...params})
        // if(success){
          let list = projectList
          if(!list.length){
            return
          }
          areaList =  list.map((item,index)=>{
            return {
              label: item.areaName,
              value: item.areaId,
              children: item.projectList
            }
          })
          yield put({type: 'updateStore', payload: {areaList}})
          if(sessionStorage.competingGoodsListId){
            yield put({type: 'filterProjectList', payload: {areaId:sessionStorage.competingGoodsListId}})
          }
        // }
      },
      *deleteFun({payload},{put,select,call}){
        let params = {
          id: payload.id,
        }
        const { success, msg, data } = yield call(deleteFun, {...params})
        let defultState = yield select(state => state[tmpModule.namespace])
        if(success){
          message.success('删除成功')
          defultState.biz.refreshListDatas(true)
        }
      },
      *filterProjectList({payload},{put,select,call}){    
        let {products,areaList} = yield select(state => state[tmpModule.namespace])
        let list = []
        for(var item of areaList){
          if(item.value == payload.areaId){
            list = item.children
          }
        }
        if(list.length){
          products =  list.map((item,index)=>{
            return {
              label: item.projectName,
              value: item.projectId,
            }
          })
        }
        yield put({type: 'updateStore', payload: {products}})
      },
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        return Object.assign({}, preState, action.payload)
      },
    }
  }
  
  export default tmpModule
  